<script setup lang="ts">
import { computed, h, ref } from 'vue';

import { useAccessStore } from '@vben/stores';

import {
  CloudDownloadOutlined,
  CloudUploadOutlined,
  LinkOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

import {
  deleteTempTable,
  importFile,
  importFileHeatExchangeStationDetail,
  importFileHeatStation,
  importFileHouse,
  importFileVillage,
} from '#/api';
// import { http } from '@vben/utils';
const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  selectedType: {
    type: String,
    default: '热源', // 默认值可以根据需要设置
  },
});
const emit = defineEmits(['onClose', 'refresh']);
const accessStore = useAccessStore();
const columns = [
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    align: 'center',
  },
  {
    title: '热源站',
    dataIndex: 'heatSourceName',
    align: 'center',
  },
  {
    title: '热源站名称(财务)',
    dataIndex: 'heatSourceNameACC',
    align: 'center',
  },
  {
    title: '投产时间',
    dataIndex: 'createdTime',
    align: 'center',
  },
  {
    title: '经度',
    dataIndex: 'longitude',
    align: 'center',
  },
  {
    title: '纬度',
    dataIndex: 'latitude',
    align: 'center',
  },
  {
    title: '热源的建设性质',
    dataIndex: 'heatSourceBelong',
    align: 'center',
  },
  {
    title: '供热模式',
    dataIndex: 'heatingMode',
    align: 'center',
  },
  {
    title: '是否完成',
    dataIndex: 'isCompleted',
    align: 'center',
  },
];
const columns_RZ = [
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    align: 'center',
  },
  {
    title: '区域',
    dataIndex: 'comNameLevel4',
    align: 'center',
  },
  {
    title: '热源站',
    dataIndex: 'heatSourceName',
    align: 'center',
  },
  {
    title: '换热站',
    dataIndex: 'heatExchangeStationName',
    align: 'center',
  },
  {
    title: '换热站名称(财务)',
    dataIndex: 'heatExchangeStationNameACC',
    align: 'center',
  },
  {
    title: '站级',
    dataIndex: 'stationLevel',
    align: 'center',
  },
  {
    title: '建筑形式',
    dataIndex: 'buildingType',
    align: 'center',
  },
  {
    title: '换热站编号',
    dataIndex: 'heatExchangeStationNumber',
    align: 'center',
  },
  {
    title: '热源形式',
    dataIndex: 'heatSourceType',
    align: 'center',
  },
];
const columns_XQ = [
  {
    title: '所属省',
    dataIndex: 'province',
    align: 'center',
  },
  {
    title: '所属市',
    dataIndex: 'city',
    align: 'center',
  },
  {
    title: '所属区/县',
    dataIndex: 'county',
    align: 'center',
  },
  {
    title: '所属换热站',
    dataIndex: 'heatExchangeStationName',
    align: 'center',
  },
  {
    title: '小区名称',
    dataIndex: 'village',
    align: 'center',
  },
  {
    title: '经度',
    dataIndex: 'longitude',
    align: 'center',
  },
  {
    title: '纬度',
    dataIndex: 'latitude',
    align: 'center',
  },
  {
    title: '收费方式',
    dataIndex: 'chargeMethod',
    align: 'center',
  },
  {
    title: '建筑年限',
    dataIndex: 'buildingYear',
    align: 'center',
  },
  {
    title: '归属小区',
    dataIndex: 'belongVillage',
    align: 'center',
  },
  {
    title: '小区地址',
    dataIndex: 'villageAddress',
    align: 'center',
  },
];
const columns_RYH = [
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    align: 'center',
  },
  {
    title: '区域',
    dataIndex: 'county',
    align: 'center',
  },
  {
    title: '小区名称',
    dataIndex: 'village',
    align: 'center',
  },
  {
    title: '楼栋',
    dataIndex: 'building',
    align: 'center',
  },
  {
    title: '单元',
    dataIndex: 'unit',
    align: 'center',
  },
  {
    title: '房间号',
    dataIndex: 'house',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '住户名称',
    dataIndex: 'holder',
    align: 'center',
  },
  {
    title: '入户状态',
    dataIndex: 'checkIn',
    align: 'center',
  },
  {
    title: '收费面积',
    dataIndex: 'feeArea',
    align: 'center',
  },
  {
    title: '名单类型',
    dataIndex: 'blacklistType',
    align: 'center',
  },
  {
    title: '使用性质',
    dataIndex: 'houseType',
    align: 'center',
  },
  {
    title: '错误提示',
    dataIndex: 'cases',
    align: 'center',
  },
];
const onClose = () => {
  emit('onClose');
};
const dataSource = ref([]);
const header = {
  Authorization: accessStore.accessToken || localStorage.getItem('token'),
};
const fileList = ref([]);
// 使用 computed 属性根据 selectedType 动态选择 columns
const dynamicColumns = computed(() => {
  switch (props.selectedType) {
    case '小区': {
      return columns_XQ;
    }
    case '热源': {
      return columns;
    }
    case '热用户': {
      return columns_RYH;
    }
    case '热站': {
      return columns_RZ;
    }
    default: {
      return columns;
    } // 默认返回 '热源' 的 columns
  }
});
const uploadUrl = computed(() => {
  switch (props.selectedType) {
    case '小区': {
      return '/api/ChargeSystem/import/verifyVillageData';
    }
    case '热源': {
      return '/api/ChargeSystem/import/verifyHeatSourceData';
    }
    case '热用户': {
      return '/api/ChargeSystem/import/importHouseDetailExcel';
    }
    case '热站': {
      return '/api/ChargeSystem/import/verifyHeatExchangeStationData';
    }
    default: {
      return '/api/ChargeSystem/import/verifyHeatSourceData';
    }
  }
});
const onTemplate = () => {
  const templateMap = {
    热源: '/Execl/热源信息表.xls',
    热站: '/Execl/换热站信息表.xls',
    小区: '/Execl/小区信息表.xls',
    热用户: '/Execl/用户信息表.xls',
  };

  const templatePath =
    templateMap[props.selectedType as keyof typeof templateMap];
  if (templatePath) {
    const link = document.createElement('a');
    link.href = templatePath;
    link.download = templatePath.split('/').pop() || '';
    document.body.append(link);
    link.click();
    link.remove();
  }
};
const loading = ref(false);
const saveLoading = ref(false);

const handleUploadResponse = (res: any) => {
  if (res.data.code === 200) {
    if (props.selectedType === '热用户') {
      importFileHeatExchangeStationDetail().then((rep: any) => {
        console.log(rep);
        if (rep.data.areaProblem.lengths > 0) {
          dataSource.value = rep.data.areaProblem;
          message.warn('有错误提示，请查看表格');
        } else {
          deleteTempTable();
        }
      });
    } else {
      message.success('上传成功');
      // 清空数据
      dataSource.value = [];
      fileList.value = [];
      // 触发刷新事件
      emit('refresh');
      // 关闭弹窗
      emit('onClose');
    }
  } else {
    message.error(res.msg || '上传失败');
  }
};

const handleSave = async () => {
  if (dataSource.value.length === 0 || fileList.value.length === 0) {
    message.error('请先导入文件');
    return;
  }
  saveLoading.value = true;
  try {
    const uploadFunctions = {
      热源: importFile,
      热站: importFileHeatStation,
      小区: importFileVillage,
      热用户: importFileHouse,
    };
    const uploadFunction =
      uploadFunctions[props.selectedType as keyof typeof uploadFunctions];
    if (uploadFunction) {
      await uploadFunction().then(handleUploadResponse);
    }
  } catch {
    saveLoading.value = false;
  } finally {
    saveLoading.value = false;
  }
};

const handleChange = async (info: any) => {
  const { file } = info;
  console.log(info);
  if (file.status === 'uploading') {
    loading.value = true;
    return;
  }

  if (file.status === 'done') {
    const { response } = file;
    if (response.code === 200) {
      try {
        // 设置表格数据
        dataSource.value = response.data;
        message.success('导入成功');
      } catch {
        message.error('导入失败，请重试');
      }
    } else {
      message.error(response.msg || '导入失败');
    }
  } else if (file.status === 'error') {
    message.error(`${file.name} 文件上传失败`);
  }

  loading.value = false;
};
</script>

<template>
  <div>
    <a-modal
      v-model:open="props.open"
      title="导入数据"
      width="1200px"
      :footer="null"
      @cancel="onClose"
    >
      <div class="flex">
        <a-upload
          v-model:file-list="fileList"
          name="file"
          :action="uploadUrl"
          :headers="header"
          @change="handleChange"
          :show-upload-list="false"
          :disabled="loading"
        >
          <a-button
            type="primary"
            :icon="h(CloudDownloadOutlined)"
            :loading="loading"
          >
            导入文件
          </a-button>
        </a-upload>
        <a-button
          type="primary"
          :icon="h(LinkOutlined)"
          @click="onTemplate"
          class="ml-2 mr-2"
        >
          导出模板
        </a-button>
        <a-button
          type="primary"
          :disabled="dataSource.length === 0"
          :icon="h(CloudUploadOutlined)"
          :loading="saveLoading"
          @click="handleSave"
        >
          上传
        </a-button>
      </div>
      <a-table
        :columns="dynamicColumns"
        :data-source="dataSource"
        :pagination="false"
        :row-key="(record: any, index: number) => index"
      >
        <template #bodyCell="{ column, record }">
          <div v-if="column.dataIndex === 'isCompleted'">
            <a-tag
              :bordered="false"
              color="success"
              v-if="record.isCompleted == 1"
            >
              完成
            </a-tag>
            <a-tag :bordered="false" color="error" v-else>未完成</a-tag>
          </div>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<style scoped></style>
